import React from 'react'
import Modal from 'react-modal'

import Flex from 'antd-mobile/lib/flex'
import Carousel, { CarouselProps } from 'antd-mobile/lib/carousel'
import WingBlank from 'antd-mobile/lib/wing-blank'
import WhiteSpace from 'antd-mobile/lib/white-space'

import SearchBar from '../../Components/SearchBar/SearchBar'
import ActivityCard from '../../Components/ActivityCard/ActivityCard'
import Notify from '../../Components/Notify/Notify'
import { fetchShopIndex } from '../../tools/fetch'
import { domain } from '../../tools/config/var'

import 'antd-mobile/lib/flex/style/css'
import 'antd-mobile/lib/carousel/style/css'
import 'antd-mobile/lib/wing-blank/style/css'
import 'antd-mobile/lib/white-space/style/css'
import './main.scss'

type BannerProps = {
  data: Record<string, string>[]
} & CarouselProps
class Banner extends React.PureComponent<BannerProps, {}> {
  readonly state = {
    slideIndex: 0,
    // 一定要分一个指示器index出来，不然 beforeChange -> setState -> beforeChange 死循环了
    dotIndex: 0,
  }

  public componentDidMount () {
    window.dispatchEvent(new Event('resize'))
  }

  public componentDidUpdate (prevProps: BannerProps) {
    if (this.props.data.length !== prevProps.data.length) {
      // After the new child element is rendered, change the slideIndex
      // https://github.com/FormidableLabs/nuka-carousel/issues/327
      this.setState({ slideIndex: this.props.data.length - 1 });
    }
  }

  private changeHandle = (from: number, to: number) => {
    try {
      this.props.beforeChange && this.props.beforeChange(from, to)
    } catch (err) {
      //
    }
    // 调整指示器
    this.setState({
      dotIndex: to
    })
  }


  render () {
    const { data, beforeChange, ...rest } = this.props
    if (!data.length) {
      return (
        <div className="com_carousel_container">
          <div className="carousel_items_container">
            <a className="img_container"></a>
          </div>
          <div className="com_carousel_dots_container">
            <div className="com_carousel_dots">
              <span className={`com_carousel_dot`}></span>
            </div>
          </div>
        </div>

      )
    }
    return (
      <div className="com_carousel_container">
        <WingBlank size="lg">
          <Carousel
            className="carousel_items_container"
            dots={false}
            autoplay={true}
            infinite={true}
            selectedIndex={this.state.slideIndex}
            beforeChange={this.changeHandle}
            {...rest}
          >
            {
              data.sort(function (now, next) {
                return parseInt(now.sort) - parseInt(next.sort)
              }).map((val, index) => {
                if (!val.imgurl) {
                  return undefined
                }
                return (
                  <a className="img_container" key={val.id}
                    href={val.url}
                    style={{backgroundImage: `url(${domain}${val.imgurl})`}}
                  >
                    <img src={`${domain}${val.imgurl}`} x-sort={val.sort} alt={val.name}
                    />
                  </a>
                )
              })
            }
          </Carousel>
          <div className="com_carousel_dots_container">
            <div className="com_carousel_dots">
              {
                data.map((val, index) => (<span key={index} className={`com_carousel_dot ${this.state.dotIndex === index ? 'active' : ''}`}></span>))
              }
            </div>
          </div>
        </WingBlank>
      </div>
    )
  }
}

type State = {
  modalIsOpen: boolean
  bannerData: Record<string, string>[]
  quickjumpData: Record<string, string>[]
  tagedData: Record<string, string>[]
  typedData: Record<string, string>[],
  officalQr: Record<string, string>
}

export default class Main extends React.PureComponent<{}, State> {
  readonly state: State = {
    modalIsOpen: false,
    bannerData: [],
    quickjumpData: [],
    tagedData: [],
    typedData: [],
    officalQr: {}
  }

  private customStyles: Modal.Styles  = {
    overlay: {
      backgroundColor: 'rgba(0, 0, 0, 0.4)'
    },
    content : {
      top: '50%',
      left: '0',
      right: '0',
      border: 'none',
      position: 'relative',
      backgroundColor: '#fff',
      borderRadius: '4px',
      width: '80%',
      marginLeft: 'auto',
      marginRight: 'auto',
      padding: '20px',
      transform: 'translate(0, -50%)'
    }
  };

  public async componentDidMount () {
    const cachedDataString = localStorage.getItem(`${btoa(location.href)}`)
    if (cachedDataString) {
      try {
        this.parseData(JSON.parse(cachedDataString))
      } catch (err) {
        // 本地数据出错
      }
    }
    const pageData = await fetchShopIndex()
    console.log(pageData)
    if (pageData.status === '1') {
      const pageDataString = JSON.stringify(pageData)
      if (pageDataString === cachedDataString) {
        return
      }
      this.parseData(pageData)
      localStorage.setItem(`${btoa(location.href)}`, pageDataString)
    } else {
      // 出错了
    }
  }

  private parseData (pageData: Record<string, any>) {
    const {
      indexalbum: bannerData,
      tubiao: quickjumpData,
      lab: tagedData,
      slab: typedData,
      qrcode: officalQr,
    } = pageData.data
    bannerData && this.setState({
      bannerData: bannerData,
      quickjumpData: quickjumpData,
      tagedData: tagedData,
      typedData: typedData,
      officalQr: officalQr,
    })
  }

  private openModal =  () => {
    this.setState({
      modalIsOpen: true
    })
  }

  private closeModal =  () => {
    this.setState({
      modalIsOpen: false
    })
  }

  public render () {
    return (
      <div className="body_fill">
        {/* 关注提醒 */}
        <Notify icon={`test`} btn_text={`关注我们`} onClick={this.openModal} />
        {/* 公众号弹层 */}
        <Modal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal}
          contentLabel="Example Modal"
          style={this.customStyles}
          className="com_modal_office_qr"
        >
          <div className="modal_title">{this.state.officalQr.wxname}</div>
          <div className="modal_image">
            <img src={`${domain}${this.state.officalQr.imgurl}`} alt=""/>
          </div>
        </Modal>

        {/* 搜索栏 */}
        <form action={`${domain}/Shop/goodslist`} method="get">
          <SearchBar name="name" />
        </form>

        <WhiteSpace />

        {/* banner滚动 */}
        <Banner
          data={this.state.bannerData}
        />

        {/* 快速跳转 */}
        <Flex justify='center' className="quick_jump">
          {
            this.state.quickjumpData.map(val => {
              return (
                <Flex.Item key={val.id}>
                  <a href={`${domain}${val.summary}`} className="quick_jump_item">
                    <div className="icon">
                      <img src={`${domain}${val.imgurl}`} alt=""/>
                    </div>
                    <div className="text">{val.name}</div>
                  </a>
                </Flex.Item>
              )
            })
          }
        </Flex>
        <WhiteSpace />

        {/* 活动海报 */}
        {
          this.state.tagedData.map(val => (
            <div key={val.id}>
              <ActivityCard data={val} type="taged" />
              <WhiteSpace />
            </div>
          ))
        }
        {
          this.state.typedData.map(val => (
            <div key={val.id}>
              <ActivityCard data={val} type="typed" />
              <WhiteSpace />
            </div>
          ))
        }

        <div className="page_bottom">
          <div className="bottom_tips">万裕科技公司</div>
        </div>
      </div>
    )
  }
}
